﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

/// <summary>
/// 针对不同目录，验证不同角色
/// </summary>
public class AuthRole
{
	public AuthRole()
	{

    }

    #region 成员
    /// <summary>
    /// 验证目录
    /// </summary>
    protected static string[] Role_Directory = null;
    /// <summary>
    /// 通过角色
    /// </summary>
    protected static string[] Role_Allow = null;
    /// <summary>
    /// 登录页面
    /// </summary>
    protected static string[] Role_Login = null;
    #endregion

    #region 方法
    /// <summary>
    /// 返回配制键值
    /// </summary>    
    public static string GetAppSettings(string name)
    {
        return Convert.ToString(ConfigurationManager.AppSettings[name]);
    } 
    /// <summary>
    /// 从配制文件读取信息
    /// </summary>
    public static void Init()
    {
        Role_Directory = GetAppSettings("Role_Directory").Split(',');
        Role_Allow = GetAppSettings("Role_Allow").Split(',');
        Role_Login = GetAppSettings("Role_Login").Split(',');
    }
    /// <summary>
    /// 目录验证
    /// </summary>
    public static bool DirectoryValidate(HttpContext context, string virtualPath)
    {
        bool result = false;
        string mapdir = UIMethod.ApplicationPath();//程序头目录
        int MatchID = CheckDirectory(mapdir, virtualPath);
        if (MatchID != -1)
        {
            //没有登录或不是指定角色，则转到指定登录页
            if (!context.User.IsInRole(Role_Allow[MatchID]))
            {
                //对应的登录页面
                StringBuilder rolelogin = new StringBuilder();
                rolelogin.Append(Role_Directory[MatchID]).Append(Role_Login[MatchID])
                    .Append("?ReturnUrl=").Append(context.Server.UrlEncode(virtualPath + context.Request.Url.Query));
                string reurl = UIMethod.HttpExcelRoot(rolelogin.ToString());

                context.Response.Redirect(reurl);
                result = true;
            }
        }
        return result;
    }
    /// <summary>
    /// 是否有匹配目录
    /// </summary>
    /// <param name="appDir">应用程序头目录 例：/website</param>
    /// <param name="virtualPath">虚拟路径 例：/index</param>
    /// <returns>-1 没有</returns>
    public static int CheckDirectory(string appDir, string virtualPath)
    {
        appDir = appDir.ToLower();
        virtualPath = virtualPath.ToLower();
        int result = -1; //匹配数组编号
        //获取该目录，是否需要角色验证        
        for (int i = 0; i < Role_Directory.Length; i++)
        {
            string tempurl = appDir + Role_Directory[i].ToLower();
            string loginurl = tempurl + Role_Login[i].ToLower();
            //是否登录页
            if (virtualPath == loginurl) { break; }
            //该路径是否需要角色验证
            if (virtualPath.IndexOf(tempurl.ToLower()) == 0)
            {
                result = i;
                break;
            }
        }
        return result;
    }

    /// <summary>
    /// 登录验证
    /// </summary>
    public static bool Login(string UserName, string PassWord)
    {
        bool result = false;
        int mid = 0;//用户编号
        string role = string.Empty;//角色

        DataEntity.tab_Admin u = new DataEntity.tab_Admin();
        u.Login(UserName, PassWord);
        if (!u.IsEmpty)
        {
            mid = u.adm_ID.Value;
            role = u.adm_RoleType;
        }        
        
        //有该用户
        if (mid != 0)
        {
            CurrentUserInfo = u;
            HttpContext hc = HttpContext.Current;
            //设置角色票据
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                1,
                mid.ToString(),
                DateTime.Now,
                DateTime.Now.AddMinutes(20),
                true,
                role,     //角色
                "/"
                );

            // Encrypt the ticket.
            string encTicket = FormsAuthentication.Encrypt(ticket);            
            
            // Create the session
            hc.Response.Cookies["AuthCookie"].Value = encTicket;
            hc.Response.Cookies["AuthCookie"].Expires = DateTime.Now.AddMinutes(20);            
                        
            //记录最后次登录名
            hc.Response.Cookies["LoginName"].Value = UserName;
            hc.Response.Cookies["LoginName"].Expires = DateTime.Now.AddYears(1);

            result = true;
        }
        return result;
    }

    /// <summary>
    /// 获取或设置 当前用户信息
    /// </summary>
    public static DataEntity.tab_Admin CurrentUserInfo
    {
        get
        {
            try
            {
                DataEntity.tab_Admin u = new DataEntity.tab_Admin();
                object cui = HttpContext.Current.Session["UserInfo"];
                if (cui == null)
                {
                    u.Select(UIMethod.GetUserID());
                    HttpContext.Current.Session["UserInfo"] = u;
                }
                else { u = (DataEntity.tab_Admin)cui; }

                return u;
            }
            catch { SignOut(); HttpContext.Current.Response.Redirect("~/", true); }
            return null;
        }
        set { HttpContext.Current.Session["UserInfo"] = value; }
    }

    /// <summary>
    /// 获取最后次登录的用户名称
    /// </summary>
    public static string LastLoginName
    {
        get 
        {
            try
            {
                return Convert.ToString(HttpContext.Current.Request.Cookies["LoginName"].Value);
            }
            catch { }

            return string.Empty;
        }
    }

    /// <summary>
    /// 注销登录
    /// </summary>
    public static void SignOut()
    {
        HttpContext.Current.Response.Cookies["AuthCookie"].Value = string.Empty;
        //HttpContext.Current.Response.Cookies["AuthCookie"].Expires = DateTime.MinValue;
        //HttpContext.Current.Request.Cookies.Remove("AuthCookie");
    }

    /// <summary>
    /// 跳转到原始请求位置或一个默认地址
    /// </summary>
    public static void Redirect(string DefaultURL)
    {
        HttpContext hc = HttpContext.Current;
        try
        {
            // Redirect back to original URL.                
            hc.Response.Redirect(hc.Request["ReturnUrl"]);
        }
        catch (System.ArgumentNullException)
        { hc.Response.Redirect(DefaultURL); }
    }

    public static void Redirect()
    {
        Redirect("Admin_Index.htm");
    }
    #endregion
}
